﻿/// <reference path="jquery-1.9.1.js" />
///debugger
if (typeof (EntityName) == 'undefined') {
    //表单名称
    EntityName = 'test_test';

    //表单ID
    FormId = '06e031d1-9429-4293-b3f9-a22f5e2cdd7e';

    //表单数据
    XFormData = { "test_testId": "06e031d1-9429-4293-b3f9-a22f5e2cdd7e", "test_name": "测试1", "test_int": 10, "test_bit": true, "test_float": 2.7, "test_ntext": "aaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddd", "test_datetime": "2015-08-17 09:21", "test_picklist_stringmap": 1, "test_picklist_common": 1, "test_lookup": { "id": "4808266a-07d6-4b59-8160-846967f5d5d2", "Name": "lookup1", "EntityName": "test_lookup" } };

    //列表数据
    var ListData = { "Total": 1, "Size": 10, "Index": 0, "List": [{ "test_testId": "06e031d1-9429-4293-b3f9-a22f5e2cdd7e", "test_name": "测试1", "test_int": 10, "test_bit": true, "test_float": 2.7, "test_ntext": "aaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddd", "test_datetime": "2015-08-17 09:21", "test_picklist_stringmap": 1, "test_picklist_common": 1, "test_lookup": { "id": "4808266a-07d6-4b59-8160-846967f5d5d2", "Name": "lookup1", "EntityName": "test_lookup" } }] };

    //实体字段定义
    EntityField = { "test_testId": { "Cansearchable": true, "DisplayName": "测试实体Id", "Type": "key" }, "test_name": { "Cansearchable": true, "DisplayName": "名称", "IsPrimaryAtt": true, "Length": 200, "Type": "nvarchar" }, "test_int": { "Cansearchable": true, "DisplayName": "int字段", "Type": "int" }, "test_bit": { "Cansearchable": true, "DisplayName": "bit字段", "Type": "bit" }, "test_float": { "Cansearchable": true, "DisplayName": "float字段", "Type": "float" }, "test_ntext": { "Cansearchable": true, "DisplayName": "ntext字段", "Type": "ntext" }, "test_datetime": { "Cansearchable": true, "DisplayName": "datetime字段", "Type": "datetime" }, "test_picklist_stringmap": { "Cansearchable": true, "DisplayName": "picklist字段-stringmap", "Type": "picklist" }, "test_picklist_common": { "Cansearchable": true, "DisplayName": "picklist_common", "GlobalPicklist": "test_type", "IsGlobalPicklist": true, "Type": "picklist" }, "test_lookup": { "Cansearchable": true, "DisplayName": "lookup字段", "LookupEntityName": "test_lookup", "Type": "lookup" } };

    //实体选项定义
    EntityOption = { "test_picklist_common": [{ "Text": "啊", "Value": 5 }, { "Text": "公司", "Value": 1 }, { "Text": "哈哈", "Value": 3 }], "test_picklist_stringmap": [{ "Text": "a", "Value": 1 }, { "Text": "b", "Value": 2 }] };
}


if (typeof (core) == 'undefined')
    core = {};

core.OpenEntity = function (src) {
    var etn = $(src).attr("etn");
    var oid = $(src).attr("oid");
    var Oorder1 = $("th[attname='tlm_corporatename']").index() - 1;
    var Oorder2 = $("th[attname='tlm_companycheck']").index() - 1;
    var companyname = $(src).find('td').eq(Oorder1).html();
    var Ischeck = $(src).find('td').eq(Oorder2).html();
    if (window.location.pathname.split("/")[window.location.pathname.split("/").length - 1] == "LinkView.aspx") {
        if (oid == null || oid == "") {
            $.postOpen("/Pages/DataPages/Form/FormPage.aspx?entityname=" + ((!!etn) ? etn : EntityName), encodeURIComponent('{ "' + $.getQueryString("attribute") + '":{"oid":"' + $.getQueryString("linkentityid") + '","value":"' + $.getQueryString("entitydisplayname") + '"} }'), "_blank");
        }
        else {
            window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=" + etn + "&id=" + oid);
        }
    }
    else {
        if (oid == null || oid == "") {
            window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=" + ((!!etn) ? etn : EntityName));
        }
        else {
            if (Ischeck == '未校验')
                window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=" + etn + "&id=" + oid);
            else if (Ischeck == '已校验') {
                var postdata = { "tlm_parentcustomerid": { "value": companyname } };
                $.postOpen("/Pages/DataPages/Form/FormPage.aspx?entityname=" + etn + "&id=" + oid, JSON.stringify(postdata), "_blank");
            }
            else
                window.open("/Pages/DataPages/Form/FormPage.aspx?entityname=" + etn + "&id=" + oid);
        }
    }
}


core.Assign = function () {
    var Checked = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    var num = Checked.length;
    if (num <= 0) return;
    $(core.View.CreateLookupListModal()).on('click', function () {
        $('#myModal').modal('hide');
        core.View.CreateModal("提示", "<div  style=\"text-align:center\"><p id=\"myModelContent\" >  </p>\
                        <div id=\"progress\" class=\"progress \" style=\"opacity:0;height:0px\">\
                            <div  id=\"progress_bar\" class=\"progress-bar progress-bar-info\" role=\"progressbar\" aria-valuemax=\"100\" aria-valuemin=\"0\" style=\"width: 0% ;\">\
                                <span class=\"sr-only\">60%</span>\
                            </div>\
                        </div></div>", "确定", "关闭");
        core.AssignConfirmed(0, core.Lookup.GetSelectedOid);
    });
    core.Lookup.BindLookupList("systemuser");
    $('#myModalLabel').html("请选择");
    $('#myModal').modal({ backdrop: 'static', keyboard: false });
}

core.AssignConfirmed = function (index, OwningUserId, list) {
    if (index == 0) {
        $("#myModal").modal({ backdrop: 'static', keyboard: false });
        list = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    }

    var num = list.length;
    core.showProgressBar(index, num, "修改");
    if (index < num) {
        $.ajax({
            type: "post",
            async: true,
            url: "/Service/Data/AssignOwningUser.ashx",
            dataType: "json",
            data: { entityname: EntityName, targetid: list.eq(index).attr("oid"), owninguserid: OwningUserId },
            success: function (data, textStatus) {
                if (data.ResultCode == 0) {
                    core.AssignConfirmed(index + 1, OwningUserId, list);
                } else {
                    core.ShowProgressError(index, num, data, "修改");
                }
            },
            error: function (xhr, textStatus, errorThrow) {
                $('#myModal').modal('hide');
                Common.AjaxError(xhr, textStatus, errorThrow);
            }
        });
    }
}

core.SoftDelete = function () {
    core.View.CreateModal("提示", "<div  style=\"text-align:center\"><p id=\"myModelContent\">  </p>\
                        <div id=\"progress\" class=\"progress \" style=\"opacity:0;height:0px\">\
                            <div  id=\"progress_bar\" class=\"progress-bar progress-bar-info\" role=\"progressbar\" aria-valuemax=\"100\" aria-valuemin=\"0\" style=\"width: 0% ;\">\
                                <span class=\"sr-only\">60%</span>\
                            </div>\
                        </div></div>", "删除", "关闭");
    $('#ModalButton1').on('click', function ()
    {
        core.DoDelete(0);
    });
    var Checked = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    var num = Checked.length;

    $("#progress").css("opacity", "0");
    $("#progress").css("height", "0px");
    if (num == 0)
    {
        ////alert("请选择要删除的数据");
        //$('#myModelContent').html("请选择要删除的数据");
        ////禁用删除按钮
        //$('#ModalButton1').attr('disabled', "true");
        //$('#ModalButton1').css('background', '#ccc');
        return;
    }
    if (num > 0)
    {
        //启用删除按钮
        $('#myModelContent').html("确定要删除" + num + "项数据？");
        $('#ModalButton1').removeAttr('disabled');
        $('#ModalButton1').css('background', '#09c');
        //初始化进度条
        $('#progress_bar').css('width', '0%');
    }
    $("#myModal").modal({ backdrop: 'static', keyboard: false });
}


core.recoverSoftDelete = function () {
    core.View.CreateModal("提示", "<div  style=\"text-align:center\"><p id=\"myModelContent\">  </p>\
                        <div id=\"progress\" class=\"progress \" style=\"opacity:0;height:0px\">\
                            <div  id=\"progress_bar\" class=\"progress-bar progress-bar-info \" role=\"progressbar\" aria-valuemax=\"100\" aria-valuemin=\"0\" style=\"width: 0% ;\">\
                                <span class=\"sr-only\">60%</span>\
                            </div>\
                        </div></div>", "恢复", "关闭");
    $('#ModalButton1').on('click', function () {
        core.DoDelete(0,0,true);
    });
    var Checked = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    var num = Checked.length;

    $("#progress").css("opacity", "0");
    $("#progress").css("height", "0px");
    if (num == 0) {
        ////alert("请选择要删除的数据");
        //$('#myModelContent').html("请选择要删除的数据");
        ////禁用删除按钮
        //$('#ModalButton1').attr('disabled', "true");
        //$('#ModalButton1').css('background', '#ccc');
        return;
    }
    if (num > 0) {
        //启用删除按钮
        $('#myModelContent').html("确定要恢复" + num + "项数据？");
        $('#ModalButton1').removeAttr('disabled');
        $('#ModalButton1').css('background', '#09c');
        //初始化进度条
        $('#progress_bar').css('width', '0%');
    }
    $("#myModal").modal({ backdrop: 'static', keyboard: false });
}


/*********************************执行删除*********************************/
core.DoDelete = function (index, checkedItems, recoverFlag) {
    if (recoverFlag == "undefined" || recoverFlag == undefined || recoverFlag.length == 0 || recoverFlag == null) {
        recoverFlag = false;
    }
    if (index == 0)
        checkedItems = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    var num = checkedItems.length;
    core.showProgressBar(index, num, recoverFlag? "恢复":"删除");
    if (index < num) {
        $.ajax({
            type: "post",
            async: true,
            url: "/Service/Data/SoftDeleteItem.ashx",
            dataType: "json",
            data: { entityname: EntityName, id: checkedItems.eq(index).attr("oid"),action:recoverFlag? "recover":"delete" },
            success: function (data, textStatus) {
                if (data.ResultCode == 0) {
                    core.DoDelete(index + 1, checkedItems,recoverFlag);
                } else {
                    core.ShowProgressError(index, num, data, recoverFlag ? "恢复" : "删除");
                }
            },
            error: function (xhr, textStatus, errorThrow) {
                $('#myModal').modal('hide');
                Common.AjaxError(xhr, textStatus, errorThrow);
            }
        });
    }
}
core.ShowProgressError = function (index, num, data, activename) {
    $('#progress_bar').css('background-color', '#FF7E00');
    $('#myModelContent').html(activename + "第" + (index + 1) + "/ " + num + "条数据时发生错误！错误原因：" + data.ResultMessage);
}
core.showProgressBar = function (index, num, activename) {
    $("#progress").css("opacity", "1.0");
    $("#progress").css("height", "20px");
    $('#progress_bar').css('width', ((index + 1) / num) * 100 + '%');
    $('#myModelContent').html("正在" + activename + +(index + 1) + "/ " + num + "条数据！");
    //禁用删除按钮
    if (!$('#ModalButton1').attr('disabled')) {
        $('#ModalButton1').attr('disabled', "true");
        $('#ModalButton1').css('background', '#ccc');
    }
    if (num == index) {
        //alert("删除成功");
        $('#myModelContent').html("成功" + activename + num + "条数据！");
        $('#ModalButton1').attr('disabled', "true");
        $('#ModalButton1').css('background', '#ccc');
        //刷新UI
        core.View.Refresh(id);
    }

}

/*********************************全选*********************************/
core.CheckAll = function () {
    var Checkall = $("[name=ListContainer] input[type=checkbox][id='checkall']");
    var tr = $('#' + id + ' [name=ListContainer] tbody tr');
    if (Checkall.prop("checked")) {
        tr.css("background-color", "#CCE8FF");
    } else {
        tr.css("background-color", "#fff");
    }
    $("[name=ListContainer] input[type=checkbox][oid]").each(function () {
        $(this).prop('checked', Checkall.prop("checked"));
    });

}

core.Restore = function () {


    var Checked = $("[name=ListContainer] input[type=checkbox]:checked");
    var num = Checked.length;
    var isRestore = 0;
    if (num == 0) {
        alert("请选择要还原的数据");
        return;
    }
    if (confirm("是否确定还原？")) {
        Checked.each(function () {
            $.ajax({
                type: "post",
                async: false,
                url: "/Service/Data/RestoreItem.ashx",
                data: { entityname: $(this).attr("etn"), id: $(this).attr("oid") },
                success: function (data, textStatus) {
                    isRestore += 1;
                },
                error: Common.AjaxError
            });
        });
        if (num == isRestore) {
            alert("还原成功");
        }
        //刷新UI
        core.View.Refresh(id);
    }

}

core.Util = {}
core.Util.GetOptionText = function (options, value) {
    var text = "";
    $.each(options, function (i, v) {
        if (v.Value == value) {
            text = v.Text;
            return false;
        }
    });
    return text;
}
core.Util.CreateOptions = function (options, value) {
    var optionTemplate = '<option value="{0}" {2}>{1}</option>';
    var optionsHtml = '<option value="" >-请选择-</option>';
    $.each(options, function (i, v) {
        if (typeof (value) != 'undefined' && typeof (v.Value) != 'undefined'
            && value != null && v.Value != null
            && (value.toString().toLowerCase() == v.Value.toString().toLowerCase()))
            optionsHtml += String.format(optionTemplate, v.Value, v.Text, "selected");
        else
            optionsHtml += String.format(optionTemplate, v.Value, v.Text, "");
    });
    return optionsHtml;
}
core.Util.CreateRadios = function (name, options, value) {
    var radioTemplate = '<label class="radio-inline">\
                              <input name="{0}" type="radio" id="{1}" value="{2}" {3}> {4}\
                          </label>';
    var radiosHtml = "";
    $.each(options, function (i, v) {
        if (typeof (value) != 'undefined' && value == v.Value)
            radiosHtml += String.format(radioTemplate, name, name + i, v.Value, "checked", v.Text);
        else
            radiosHtml += String.format(radioTemplate, name, name + i, v.Value, "", v.Text);
    });
    return radiosHtml;
}
core.Util.CreateCheckbox = function (name, options, value) {
    var radioTemplate = '<a style="color:#999"><label for="{1}"style="cursor:pointer"><input style="cursor:pointer" name="{0}" type="checkbox" id="{1}" value="{2}" {3}> {4}</label></a></br>';

    var radiosHtml = "";
    $.each(options, function (i, v) {
        if (typeof (value) != 'undefined' && value == v.Value)
            radiosHtml += String.format(radioTemplate, name, name + i, v.Value, "checked", v.Text);
        else
            radiosHtml += String.format(radioTemplate, name, name + i, v.Value, "", v.Text);
    });
    return radiosHtml;
}

core.Util.SaveData = function (fun, beforeSave, aftersave) {

    //必填字段检查
    var IsNullableCheck = true;
    $.each(EntityField, function (k, v) {
        if ((!v.IsNullable)
            && k != "createdon"
            && k != "createdby"
            && k != "modifiedon"
            && k != "modifiedby"
            && k != "owninguser"
            && k != "owningbusinessunit"
            && k != "deletionstatecode"
            && ($("#" + k).val() == "")
            ) {
            alert("保存失败，【" + $("label[for=" + k + "]").text() + "】不能为空！");
            IsNullableCheck = false;
            return false;
        }
    });

    if ((beforeSave == null || (beforeSave != null && (beforeSave() == false ? false : true))) && IsNullableCheck) {

        var entityData = core.Form.GetEntityData();
        //  var id = typeof (FormId) == 'undefined' ? null : FormId;
        var id = (FormId =="")? null : FormId;
        entityData[EntityName + "id"] = id;
        var json = JSON.stringify(entityData);

        $.ajax({
            type: "post",
            url: "/Service/Data/SaveFormData.ashx",
            dataType: "text",
            data: { entityname: EntityName, data: json, id: id },
            success: function (data, textStatus) {
                try {
                    window.opener.core.View.Refresh("ListInnerContainer");
                } catch (e) {

                }
                $.toast("保存成功!");
                
                if (aftersave == null || (aftersave != null && (aftersave() == false ? false : true)))
                {
                    if (id == null) {
                        window.location.href = "/Pages/DataPages/Form/FormPage.aspx?entityname=" + EntityName + "&id=" + data;
                    }
                }
            },
            error: function (data) {
                $.toast("保存失败!");
            }
        });
    }
}


core.ExportSinglePage = function (id) {
    var pagenum = (core.ListData[id].Index ? core.ListData[id].Index : 0);
    var pagesize = (core.View.PageParam[id] ? core.View.PageParam[id].pagesize : 50);
    core.PostAndExportExcel("/Service/Data/ExportExcel.ashx", id, pagenum, pagesize);
}

core.ExportAllPages = function (id) {
    var pagenum = 0;
    var pagesize = 1000000;
    core.PostAndExportExcel("/Service/Data/ExportExcel.ashx", id, pagenum, pagesize);
}

core.PostAndExportExcel = function (URL, id, pagenum, pagesize) {
    var tempform = document.createElement("form");
    tempform.acceptCharset = "UTF-8";
    tempform.method = 'post';
    tempform.action = URL;
    tempform.style.display = "none";
    tempform.id = "tempform";
    tempform.target = "_blank";
    var opt = document.createElement("textarea");
    opt.name = "entityname";
    opt.value = core.EntityName[id];
    tempform.appendChild(opt);

    opt = document.createElement("textarea");
    opt.name = "viewname";
    opt.value = core.ViewName[id];
    tempform.appendChild(opt);

    opt = document.createElement("textarea");
    opt.name = "filter";
    opt.value = JSON.stringify(core.View.FilterData[id]);
    tempform.appendChild(opt);

    opt = document.createElement("textarea");
    opt.name = "order";
    opt.value = String.format("{0} {1} ", core.View.Orderby[id].att, core.View.Orderby[id].value);
    tempform.appendChild(opt);

    opt = document.createElement("textarea");
    opt.name = "pagenum";
    opt.value = pagenum;
    tempform.appendChild(opt);

    opt = document.createElement("textarea");
    opt.name = "pagesize";
    opt.value = pagesize;
    tempform.appendChild(opt);

    $('body').append(tempform);

    tempform.submit();
    $(tempform).remove();
}

/************************************************************** 公共方法 ***************************************************************/
//获取url参数值
String.GetQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(decodeURI(r[2])); return null;
}

//格式化url参数
String.queryFormat = function (arr) {
    var queryStr = "";
    $.each(arr, function (i, v) {
        if (i == 0)
            queryStr += String.format('?{0}={1}', v.ParamsName, v.ParamsValue);
        else
            queryStr += String.format('&{0}={1}', v.ParamsName, v.ParamsValue);
    });
    return queryStr;
}

//字符串格式化
String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");

        s = s.replace(reg, arguments[i + 1] == null ? "" : arguments[i + 1]);
    }

    return s;
};